#!/bin/bash

###
#  root path: /srv/kubernetes
#  root ca:  ca-key.pem, ca.pem
#  server ca: kubernetes-key.pem kubernetes.pem
#  apiServer 的各个组件使用的客户端证书:  admin.pem admin-key.pem
###

# 创建集群的 root CA
# CA的CommonName不是必须为kube-ca，可以随意指定
mkdir -p /srv/kubernetes
cd /srv/kubernetes
# ===> ca-key.pem
openssl genrsa -out ca-key.pem 2048
# ===> ca.pem
openssl req -x509 -new -nodes -key ca-key.pem -days 10000 -out ca.pem -subj "/CN=kube-ca"

# 创建apiServer的私钥、服务端证书
# ====> 注意替换 ip 1,2,3
cat >> openssl.cnf <<EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = kubernetes
DNS.2 = kubernetes.default
DNS.3 = kubernetes.default.svc
DNS.4 = kubernetes.default.svc.cluster.local
DNS.5 = localhost
DNS.6 = k8s_master
IP.1 = 127.0.0.1
IP.2 = 172.17.8.110
IP.3 = 192.168.0.13
EOF

# 创建 kubernetes 的私钥、服务端证书
# 创建私钥
# kubernetes-key.pem
openssl genrsa -out kubernetes-key.pem 2048
#创建certificate signing request文件 kubernetes.csr，里面包含的 kubernetes 的公开信息，如：公钥、名称、可访问地址#
# kubernetes.csr
openssl req -new -key kubernetes-key.pem -out kubernetes.csr -subj "/CN=kube-master" -config openssl.cnf
#生成经过CA签署的服务端证书，里面包含服务端信息、CA的公钥，以及经CA私钥加密的服务端信息的hash值#
# kubernetes.pem
openssl x509 -req -in kubernetes.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out kubernetes.pem -days 9000 -extensions v3_req -extfile openssl.cnf

# 创建访问 apiServer 的各个组件使用的客户端证书
# admin-key.pem
openssl genrsa -out admin-key.pem 2048
# admin.csr
openssl req -new -key admin-key.pem -out admin.csr -subj "/CN=172.17.8.110"
# admin.pem
openssl x509 -req -in admin.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out admin.pem -days 9000

## 生成 Controller Manager 与 Scheduler 进程共用的证书和私钥
# cm_client_key.pem
openssl genrsa -out cm_client_key.pem 2048
# cm_client.csr
openssl req -new -key  cm_client_key.pem -out cm_client.csr -subj "/CN=172.17.8.110"
# cm_client.pem
openssl x509 -req -in cm_client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cm_client.pem -days 9000




# move to other path
cat ./kubernetes.pem > /etc/kubernetes/ssl/kubernetes.pem
cat ./kubernetes-key.pem > /etc/kubernetes/ssl/kubernetes-key.pem
cat ./ca.pem >  /etc/kubernetes/ssl/ca.pem
cat ./ca-key.pem > /etc/kubernetes/ssl/ca-key.pem
cat ./admin.pem > /etc/kubernetes/admin.pem
cat ./admin-key.pem > /etc/kubernetes/admin-key.pem
cat ./cm_client_key.pem > /etc/kubernetes/cm_client_key.pem
cat ./cm_client.pem > /etc/kubernetes/cm_client.pem


# test
# curl https://172.17.8.110:6443/api/v1/nodes --cert /srv/kubernetes/cm_client.pem --key /srv/kubernetes/cm_client_key.pem --cacert /srv/kubernetes/ca.pem
